package com.techysky.controller;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.techysky.annoation.Operation;
import com.techysky.entity.SpareHistory;
import com.techysky.entity.SpareManage;
import com.techysky.entity.User;
import com.techysky.repository.SpareHistoryRepository;
import com.techysky.repository.SpareRepository;
import com.techysky.shiro.R;

@Controller
@RequestMapping("/Spare")
public class SpareController implements Serializable {
	private static final long serialVersionUID = 1L;
	String sn="spareName";
	String sp="spare";
	String st="storage";
	String sr="storage-record";
	String or="out-record";
	String cd="createDate";
	String se="search";
	@Autowired
	private transient SpareRepository spareRepository;
	@Autowired
	private transient SpareHistoryRepository spareHistoryRepository;
	@RequestMapping({"/SpareM/spare"})
	@ResponseBody
	public Object spare(  int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid(pageable, search);
	}
	
	@RequestMapping({"/SpareM/out"})
	@ResponseBody
	public Object out(  int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid(pageable, search);
	}
	@RequestMapping({"/SpareM/storage"})
	@ResponseBody
	public Object storage(  int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid(pageable, search);
	}
	@RequestMapping({"/SpareM/records"})
	@ResponseBody
	public Object records(  int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid(pageable, search);
	}
	public List<SpareManage> grid( PageRequest pageable, String search) {
		return spareRepository.findAll((Root<SpareManage> root, CriteriaQuery<?> query, CriteriaBuilder cb)
						->{
						List<Predicate> predicate = new ArrayList<>();

						if (!StringUtils.isBlank(search)) {
							Path<String> name = root.get(sn);
							Predicate p = cb.like(name, "%" + search + "%");
							predicate.add(p);
						}
						Predicate[] pre = new Predicate[predicate.size()];
						return query.where(predicate.toArray(pre)).getRestriction();
					}
				, pageable).getContent();			
	}
	@RequestMapping("/SpareM/storage-record")
	@ResponseBody
	public Object operator3( int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid3(pageable, search);
	}
	public List<SpareHistory> grid3(PageRequest pageable, String search) {
			 return  spareHistoryRepository.findAll((Root<SpareHistory> root, CriteriaQuery<?> query, CriteriaBuilder cb)
					 ->{
						List<Predicate> predicate = new ArrayList<>();
						if (!StringUtils.isBlank(search)) {
							Path<String> name = root.get(sn);
							Path<String> code = root.get("code");
							Predicate p = cb.and(cb.like(name, "%" + search + "%"),cb.equal(code, "入库"));
							predicate.add(p);
						}else{
							Path<String> code = root.get("code");
							Predicate p = cb.equal(code, "入库");
							predicate.add(p);
						}
						Predicate[] pre = new Predicate[predicate.size()];
						return query.where(predicate.toArray(pre)).getRestriction();
					}
				, pageable).getContent();
	        }
	@RequestMapping("/SpareM/out-record")
	@ResponseBody
	public Object operator4(int pageNo, int pageSize,  HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		// 查询数据
		return grid4(pageable, search);
	}
	private List<SpareHistory> grid4( PageRequest pageable,  String search) {
		return   spareHistoryRepository.findAll((Root<SpareHistory> root, CriteriaQuery<?> query, CriteriaBuilder cb)
						->{
						List<Predicate> predicate = new ArrayList<>();
						if (!StringUtils.isBlank(search)) {
							Path<String> name = root.get(sn);
							Path<String> code = root.get("code");
							Predicate p = cb.and(cb.like(name, "%" + search + "%"),cb.equal(code, "出库"));
							predicate.add(p);
						}else{
							Path<String> code = root.get("code");
							Predicate p =cb.equal(code, "出库");
							predicate.add(p);
						}
						Predicate[] pre = new Predicate[predicate.size()];
						return query.where(predicate.toArray(pre)).getRestriction();
					}
				, pageable).getContent();		
	}
	@RequestMapping(value = "/SpareS/storage-record")
	@ResponseBody
	public Object operator2( int pageNo, int pageSize, HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		String search2 = request.getParameter("search2");
		String search3 = request.getParameter("search3");
		String search4 = request.getParameter("search4");
		// 查询数据
		return grid6( pageable, search, search2, search3, search4);
	}
	private List<SpareHistory> grid6(PageRequest pageable,  String search,  String search2,  String search3,  String search4) { 
		return spareHistoryRepository.findAll((Root<SpareHistory> root, CriteriaQuery<?> query, CriteriaBuilder cb) ->{
						List<Predicate> predicate = new ArrayList<>();
						Predicate p ;
						if (!StringUtils.isBlank(search)) {
							Path<String> createDate = root.get(cd);
							p = cb.greaterThanOrEqualTo(createDate, search);
							predicate.add(p);
							}
						if (!StringUtils.isBlank(search2)) {
							Path<String> createDate2 = root.get(cd);
							String search11=search2.substring(0,9)+Integer.parseInt(search2.substring(9))+1;
							p = cb.lessThanOrEqualTo(createDate2, search11);
							predicate.add(p);
							}
						if (!StringUtils.isBlank(search3)) {
							Path<String> createUser = root.get("createUser");
							p = cb.like(createUser, "%" + search3 + "%");
							predicate.add(p);
							}
						if (!StringUtils.isBlank(search4)) {
							Path<String> spareCode = root.get("spareCode");
							p = cb.like(spareCode, "%" + search4 + "%");
							predicate.add(p);
							}
							Path<String> code = root.get("code");
							p = cb.equal(code, "入库");
							predicate.add(p);						
						Predicate[] pre = new Predicate[predicate.size()];
						return query.where(predicate.toArray(pre)).getRestriction();}
				, pageable).getContent();}
	@RequestMapping(value = "/SpareS/out-record")
	@ResponseBody
	public Object operator5( int pageNo, int pageSize, HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo-1, pageSize);
		String search = request.getParameter(se);
		String search2 = request.getParameter("search2");
		String search3 = request.getParameter("search3");
		String search4 = request.getParameter("search4");
		// 查询数据
		return grid7(pageable,search, search2, search3, search4);
	}
	private List<SpareHistory> grid7(PageRequest pageable,  String search,  String search2,  String search3,  String search4) { 
		return spareHistoryRepository.findAll((Root<SpareHistory> root, CriteriaQuery<?> query, CriteriaBuilder cb) ->{
						List<Predicate> predicate = new ArrayList<>();
						Predicate p ;
						if (!StringUtils.isBlank(search)) {
							Path<String> createDate = root.get(cd);
							p = cb.greaterThanOrEqualTo(createDate, search);
							predicate.add(p);
							}
						if (!StringUtils.isBlank(search2)) {
							Path<String> createDate2 = root.get(cd);
							String search11=search2.substring(0,9)+Integer.parseInt(search2.substring(9))+1;
							p = cb.lessThanOrEqualTo(createDate2, search11);
							predicate.add(p);
							}
						if (!StringUtils.isBlank(search3)) {
							Path<String> createUser = root.get("createUser");
							p = cb.like(createUser, "%" + search3 + "%");
							predicate.add(p);
							}
						if (!StringUtils.isBlank(search4)) {
							Path<String> spareCode = root.get("spareCode");
							p = cb.like(spareCode, "%" + search4 + "%");
							predicate.add(p);
							}
							Path<String> code = root.get("code");
							p = cb.equal(code, "出库");
							predicate.add(p);						
						Predicate[] pre = new Predicate[predicate.size()];
						return query.where(predicate.toArray(pre)).getRestriction();}
				, pageable).getContent();}
	
		/**
	 * 备件
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/spare")
	public String spare() {
		return sp;
	}
	/**
	 * 加载供应商和备件类型
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/spareSelect")
	@ResponseBody
	public Object spareSupplier() {
		return spareRepository.findAll();
	}
	/**
	 * 添加备件
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/spare-add")
	public String spareAdd() {		
		return "spare-add";
	}
	/**
	 * 出库
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/out")
	public String out() {
		
		return "out";
	}
	/**
	 * 入库
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/storage")
	public String storage() {
		
		return st;
	}
	/**
	 * 出库记录
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/out-record")
	public String outRecord() {
		
		return or;
	}
	/**
	 * 出库高级搜索
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/out-search")
	public String outSearch() {
		
		return "out-search";
	}
	/**
	 * 入库记录
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/storage-record")
	public String storageRecord() {
		
		return sr;
	}
	/**
	 * 入库高级搜索
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/storage-search")
	public String storageSearch() {
		
		return "storage-search";
	}
	/**
	 * 库存
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/records")
	public String records() {
		
		return "records";
	}
	/**
	 * 备件新增
	 * 
	 * @param
	 * @return
	 */
	
	@RequestMapping(value = "/saveOrUpdate", method = { RequestMethod.POST })
	@ResponseBody
	public Object userGroupSaveOrUpdate( SpareManage spareManage) {
		spareRepository.saveAndFlush(spareManage);
		return spareManage;
	}
	/**
	 * 备件删除
	 * 
	 * @param
	 * @return 
	 * @return
	 */
	@RequestMapping(value = "/dele", method = { RequestMethod.POST })
	@Operation(value = "备件删除", type = "1")
	@ResponseBody
	public Object dele( String id) {
		Object obj=null;
		if (!StringUtils.isBlank(id)) {
			if (id.indexOf(',') > -1) {
				String[] spareId = id.split(",");
				for (int i = 0; i < spareId.length; i++) {
					spareRepository.delete(spareId[i]);					
					 obj=R.ok();			
				}
			} else {
				spareRepository.delete(id);
					 obj=R.ok();				
			}
			
		}
		return obj;
	}
	@RequestMapping(value = "/spareEdit", method ={RequestMethod.POST, RequestMethod.GET })
	public String spareEdit(Model model, String id) {
		SpareManage spare = spareRepository.findOne(id);
		model.addAttribute(sp, spare);
		model.addAttribute("title", "编辑备件");
		return "spare-add";
	}
	/**
	 * 验证备件序号唯一性
	 * 
	 */	
	@RequestMapping(value = "/spareNoCheck")
	@ResponseBody
	public Object  spareNoCheck(String t_spareNo) {
		List<SpareManage> spareSize =  spareRepository.findBySpareNo(t_spareNo);
		return spareSize;
	}
	/**
	 * 备件入库s
	 * 
	 * @param
	 * @return 
	 * @return
	 */	
	@RequestMapping(value = "/storage/saveOrUpdate", method = { RequestMethod.POST })
	@Operation(value = "备件入库", type = "1")
	@ResponseBody
	public Object saveStorage(HttpServletRequest request, String ids, String val,@ModelAttribute("spareHistory") SpareHistory spareHistory) {
		User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
		String getSystemTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		String getSystemTime2=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		if (!StringUtils.isBlank(ids)&&!StringUtils.isBlank(val)) {
			    String[] value = val.split(",");
			    String[] id = ids.split(",");
				for (int i = 0; i < id.length; i++) {
					SpareManage spareManage1=spareRepository.findOne(id[i]);
					int spareQuantity2=0;
					if(!StringUtils.isBlank(spareManage1.getSpareQuantity())){
						spareQuantity2=Integer.parseInt(spareManage1.getSpareQuantity());						
					}
					String spareQuantity1=String.valueOf(spareQuantity2+Integer.parseInt(value[i]));
					spareHistory.setId(id[i]+getSystemTime2);
					spareManage1.setSpareQuantity(spareQuantity1);
					spareRepository.saveAndFlush(spareManage1);	
					spareHistory.setSpareQuantity(value[i]);
					spareHistory.setCreateUser(user.getUserName());
					spareHistory.setCreateDate(getSystemTime);
					spareHistory.setSpareCode(spareManage1.getSpareCode());
					spareHistory.setSpareName(spareManage1.getSpareName());
					spareHistory.setSpareNo(spareManage1.getSpareNo());
					spareHistory.setSpareSupplier(spareManage1.getSpareSupplier());
					spareHistory.setSpareType(spareManage1.getSpareType());
					spareHistory.setCode("入库");
					spareHistoryRepository.save(spareHistory);		
				}
			}
		return st;
	}
	/**
	 * 备件出库
	 * 
	 * @param
	 * @return 
	 * @return
	 */	
	@RequestMapping(value = "/out/saveOrUpdate", method = { RequestMethod.POST })
	@Operation(value = "备件出库", type = "1")
	@ResponseBody
	public Object saveOut(HttpServletRequest request, String ids, String val,@ModelAttribute("spareHistory") SpareHistory spareHistory) {
		User user=null!=request.getSession().getAttribute("user")?(User)request.getSession().getAttribute("user"):new User();
		String getSystemTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		String getSystemTime2=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		if (!StringUtils.isBlank(ids)&&!StringUtils.isBlank(val)) {
			    String[] value = val.split(",");
			    String[] id = ids.split(",");
				for (int i = 0; i < id.length; i++) {
					SpareManage spareManage1=spareRepository.findOne(id[i]);
					int spareQuantity2=0;
					if(!StringUtils.isBlank(spareManage1.getSpareQuantity())){
						spareQuantity2=Integer.parseInt(spareManage1.getSpareQuantity());						
					}
					String spareQuantity1=String.valueOf(spareQuantity2-Integer.parseInt(value[i]));
					spareManage1.setSpareQuantity(spareQuantity1);
					spareRepository.saveAndFlush(spareManage1);	
					spareHistory.setId(id[i]+getSystemTime2);
					spareHistory.setSpareQuantity(value[i]);
					spareHistory.setCreateUser(user.getUserName());
					spareHistory.setCreateDate(getSystemTime);
					spareHistory.setSpareCode(spareManage1.getSpareCode());
					spareHistory.setSpareName(spareManage1.getSpareName());
					spareHistory.setSpareNo(spareManage1.getSpareNo());
					spareHistory.setSpareSupplier(spareManage1.getSpareSupplier());
					spareHistory.setSpareType(spareManage1.getSpareType());
					spareHistory.setCode("出库");
					spareHistoryRepository.saveAndFlush(spareHistory);		
				}
			}
		return "out";
	}
}
